
import { ESort, IGetProductsResponse, IProduct, IProductFilter, IReqCancel, IReqResult, IResult, productFilter } from '../../models';


function localFilterProducts(data: IGetProductsResponse, filter: IProductFilter, pageSize: number, pageNum: number): IGetProductsResponse {
  if (filter) {
    if (filter.sort && filter.sortProp) {
      //有排序
      if (filter.sort === ESort.Asc) {
        data.products.sort((a, b) => (a as any)[filter.sortProp!] - (b as any)[filter.sortProp!]);
      } else {
        data.products.sort((a, b) => (b as any)[filter.sortProp!] - (a as any)[filter.sortProp!]);
      }
    }
    data.products = data.products.filter(p => productFilter(p, filter));
  }
  data.products = data.products.slice(pageSize * (pageNum - 1), pageSize * pageNum);
  return data;
}
/**
 * 基础方法
 * @param filter 
 * @param pageSize 
 * @param pageNum 
 * @returns products 
 */
export function _getProducts(filter: IProductFilter, pageSize: number, pageNum: number, useTimeMs: number, useRndError: boolean): IReqResult<IGetProductsResponse> {

  let task: Promise<IResult<IGetProductsResponse>>;
  let cancelToken: IReqCancel;
  //本地模拟异步并延时1秒
  let delayHD: any = null;
  cancelToken = {
    cancel() {
      clearTimeout(delayHD);
    },
  };
  task = new Promise(res => {
    delayHD = setTimeout(() => {
      let localData = require('static/json/products.json') as IGetProductsResponse;
      //数组拷贝一份,防止本地筛选被强制修改
      localData = {
        products: [...localData.products] as IProduct[]
      };
      const data = localFilterProducts(localData as IGetProductsResponse, filter, pageSize, pageNum);

      if (useRndError) {
        if (Math.random() > 0.5) {
          //模拟一半几率接口出错
          return res({
            success: false,
            code: 500,
            error: '模拟50%概率错误',
          });
        }
      }

      return res({
        success: true,
        data: data
      });
    }, useTimeMs);
  });

  return {
    task,
    cancelToken,
  };
};

/**
 * 基础方法
 * @param filter 
 * @param pageSize 
 * @param pageNum 
 * @returns products 
 */
export function getProducts(filter: IProductFilter, pageSize: number, pageNum: number): IReqResult<IGetProductsResponse> {
  //jest的mock 延时100ms,不随机出错
  return _getProducts(filter, pageSize, pageNum, 100, false);
};
